import { defineStore } from 'pinia'
import { useUserStore } from './userStore'
import { usePermissionStore } from './permissionStore'
import { useMenuStore } from './menuStore'
import { useArticleStore } from './articleStore'
import { useLogStore } from './logStore'
// 导入其他需要的store

// 简单的加密函数（实际项目中应使用更安全的加密库）
const encrypt = (data) => {
  try {
    return btoa(encodeURIComponent(JSON.stringify(data)))
  } catch (error) {
    console.error('[AuthStore] 加密失败:', error)
    return ''
  }
}

// 简单的解密函数
const decrypt = (data) => {
  return JSON.parse(decodeURIComponent(atob(data)))
}

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    refreshToken: localStorage.getItem('refreshToken') || '',
    user: (() => {
      const raw = localStorage.getItem('user')
      const decrypted = raw ? decrypt(raw) : null
      return decrypted
    })()
  }),
  actions: {
    setAuthData({ token, refreshToken, user }) {
      this.token = token
      this.refreshToken = refreshToken
      this.user = user

      localStorage.setItem('token', token)
      localStorage.setItem('refreshToken', refreshToken)

      // 加密并保存user数据
      const encryptedUser = encrypt(user)
      localStorage.setItem('user', encryptedUser)
    },

    logout() {
      // 清除当前store的数据
      this.token = ''
      this.refreshToken = ''
      this.user = null

      // 清除localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('user')

      // 清除sessionStorage中的标签页数据
      sessionStorage.removeItem('admin_tags')

      // 清除所有其他store的数据
      try {
        // 清除用户store
        const userStore = useUserStore()
        userStore.users = []
        userStore.total = 0
        userStore.page = 1
        userStore.pageSize = 10
        userStore.query = ''
        userStore.loading = false
        userStore.currentUser = null
        userStore.rolesList = []

        // 清除权限store
        const permissionStore = usePermissionStore()
        permissionStore.permissions = []
        permissionStore.total = 0
        permissionStore.page = 1
        permissionStore.pageSize = 10
        permissionStore.loading = false
        permissionStore.currentPermission = null
        permissionStore.dialogVisible = false
        permissionStore.isEdit = false

        // 清除菜单store
        const menuStore = useMenuStore()
        menuStore.menuList = []
        menuStore.userMenuList = []

        // 清除文章store
        const articleStore = useArticleStore()
        articleStore.articles = []
        articleStore.categories = []
        articleStore.categoryTree = []
        articleStore.currentArticle = null
        articleStore.total = 0
        articleStore.page = 1
        articleStore.pageSize = 10
        articleStore.loading = false
        articleStore.submitting = false
        articleStore.queryParams = {
          title: '',
          status: '',
          categoryId: ''
        }

        // 清除日志store
        const logStore = useLogStore()
        logStore.logs = []
        logStore.total = 0
        logStore.page = 1
        logStore.pageSize = 10
        logStore.loading = false
        logStore.query = {
          startTime: null,
          endTime: null
        }

        // 如果有其他store，也在这里清除
        // 例如：角色store等

        // console.log('[AuthStore] 所有store缓存已清除')
      } catch (error) {
        console.error('[AuthStore] 清除store缓存失败:', error)
      }
    },

    setUser(user) {
      if (!user) {
        return;
      }
      // 合并原有 id，防止丢失
      const id = user.id || this.user?.id
      this.user = { ...this.user, ...user, id }
      const encryptedUser = encrypt(this.user)
      localStorage.setItem('user', encryptedUser)
    },

    // 清除所有store缓存
    clearAllStores() {
      // console.log('[AuthStore] 所有store缓存已清除')
    }
  }
})
